package com.hps.lock;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author heps
 * @date 2019/1/21 10:11
 */
public class MysqlLock {

    private Connection connection;

    private String methodName;

    public MysqlLock(Connection connection, String methodName) {
        this.connection = connection;
        this.methodName = methodName;
    }

    public boolean lock() {
        try {
            connection.setAutoCommit(false);
            String sql = "select * from methodlock where method_name = ? for update";
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1, methodName);
            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

    public void unlock() {
        try {
            connection.commit();
            DbUtil.returnConnection(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(0);
        ExecutorService executorService = Executors.newFixedThreadPool(30);
        int poolSize = 1000;
        long start = System.currentTimeMillis();
        CountDownLatch latch = new CountDownLatch(poolSize);
        for (int i = 0; i < poolSize; i++) {
            executorService.submit(() -> {
                Connection connection = DbUtil.getConnection();
                MysqlLock lock = new MysqlLock(connection, "lock");
                lock.lock();
                Integer num = list.get(list.size() - 1);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                list.add(++num);
                latch.countDown();
                lock.unlock();
            });
        }

        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(System.currentTimeMillis() - start);
        System.out.println(list);
        executorService.shutdown();
    }
}
